<?php
session_start();
require_once '../config.php';
require_once '../functions.php';

// 检查管理员是否登录
if (!is_admin_logged_in()) {
    header('Location: login.php');
    exit;
}

$message = '';
$message_type = '';

// 处理操作
if (isset($_GET['action'])) {
    $id = $_GET['id'] ?? 0;
    if (!is_numeric($id)) {
        $message = '参数错误';
        $message_type = 'error';
    } else {
        $id = (int)$id;
        switch ($_GET['action']) {
            case 'delete':
                // 删除表白
                try {
                    // 先删除相关的点赞和评论
                    $pdo->prepare("DELETE FROM likes WHERE type = 'confession' AND target_id = ?")->execute([$id]);
                    $pdo->prepare("DELETE FROM comments WHERE type = 'confession' AND target_id = ?")->execute([$id]);
                    
                    // 再删除表白本身
                    $stmt = $pdo->prepare("DELETE FROM confessions WHERE id = ?");
                    $stmt->execute([$id]);
                    
                    $message = '删除成功';
                    $message_type = 'success';
                } catch (PDOException $e) {
                    $message = '删除失败，请重试';
                    $message_type = 'error';
                }
                break;
                
            case 'top':
                // 置顶表白
                try {
                    $stmt = $pdo->prepare("UPDATE confessions SET is_top = 1 WHERE id = ?");
                    $stmt->execute([$id]);
                    $message = '置顶成功';
                    $message_type = 'success';
                } catch (PDOException $e) {
                    $message = '置顶失败，请重试';
                    $message_type = 'error';
                }
                break;
                
            case 'untop':
                // 取消置顶
                try {
                    $stmt = $pdo->prepare("UPDATE confessions SET is_top = 0 WHERE id = ?");
                    $stmt->execute([$id]);
                    $message = '取消置顶成功';
                    $message_type = 'success';
                } catch (PDOException $e) {
                    $message = '取消置顶失败，请重试';
                    $message_type = 'error';
                }
                break;
                
            case 'ban':
                // 封禁IP
                try {
                    $stmt = $pdo->prepare("SELECT ip_address FROM confessions WHERE id = ?");
                    $stmt->execute([$id]);
                    $result = $stmt->fetch();
                    
                    if ($result) {
                        $ip = $result['ip_address'];
                        $reason = "发布违规表白内容（ID: $id）";
                        
                        // 检查IP是否已被封禁
                        $stmt = $pdo->prepare("SELECT id FROM banned_ips WHERE ip_address = ?");
                        $stmt->execute([$ip]);
                        
                        if ($stmt->rowCount() == 0) {
                            $stmt = $pdo->prepare("INSERT INTO banned_ips (ip_address, reason, banned_by) VALUES (?, ?, ?)");
                            $stmt->execute([$ip, $reason, $_SESSION['admin_id']]);
                            $message = "IP $ip 已被封禁";
                            $message_type = 'success';
                        } else {
                            $message = "IP $ip 已在封禁列表中";
                            $message_type = 'info';
                        }
                    } else {
                        $message = '表白内容不存在';
                        $message_type = 'error';
                    }
                } catch (PDOException $e) {
                    $message = '封禁失败，请重试';
                    $message_type = 'error';
                }
                break;
                
            default:
                $message = '无效操作';
                $message_type = 'error';
                break;
        }
    }
}

// 处理编辑
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['edit_confession'])) {
    $id = $_POST['id'] ?? 0;
    $content = trim($_POST['content'] ?? '');
    
    if (!is_numeric($id) || empty($content)) {
        $message = '参数错误或内容为空';
        $message_type = 'error';
    } else {
        $id = (int)$id;
        
        // 检查内容是否包含违禁词
        if (has_prohibited_words($content)) {
            $message = '内容包含违禁词，请修改';
            $message_type = 'error';
        } else {
            try {
                $stmt = $pdo->prepare("UPDATE confessions SET content = ? WHERE id = ?");
                $stmt->execute([$content, $id]);
                $message = '修改成功';
                $message_type = 'success';
            } catch (PDOException $e) {
                $message = '修改失败，请重试';
                $message_type = 'error';
            }
        }
    }
}

// 获取表白列表
$stmt = $pdo->query("SELECT * FROM confessions ORDER BY is_top DESC, created_at DESC");
$confessions = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>表白管理 - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="../static/css/bootstrap.min.css">
    <link rel="stylesheet" href="../static/css/all.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            font-family: 'Arial', sans-serif;
        }
        a {
            text-decoration: none;
            outline: none;
        }
        .sidebar {
            width: 250px; /* 固定宽度 */
            height: 100vh;
            background-color: #ff8fab;
            color: white;
            padding-top: 20px;
            position: fixed;
            overflow-y: auto;
            transition: transform 0.3s ease; /* 添加过渡效果 */
            z-index: 100; /* 确保在内容上方 */
        }
        
        .sidebar-header {
            text-align: center;
            padding-bottom: 20px;
            border-bottom: 1px solid rgba(255,255,255,0.2);
            margin-bottom: 20px;
        }
        
        .sidebar-header h2 {
            margin: 0;
            font-size: 1.5rem;
        }
        
        .nav-link {
            color: white;
            padding: 10px 20px;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: all 0.3s;
            border-left: 3px solid transparent;
        }
        
        .nav-link:hover, .nav-link.active {
            background-color: rgba(255,255,255,0.1);
            color: white;
            text-decoration: none;
            border-left-color: #ffd700;
        }
        
        .main-content {
            margin-left: 250px;
            padding: 30px;
            transition: margin-left 0.3s ease; /* 添加过渡效果 */
            min-height: 100vh;
        }
        
        .page-title {
            color: #d63384;
            margin-bottom: 30px;
            font-size: 1.8rem;
        }
        
        .table-container {
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        
        .data-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .data-table th, .data-table td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #eee;
        }
        
        .data-table th {
            background-color: #fff0f3;
            color: #d63384;
            font-weight: bold;
        }
        
        .data-table tr:hover {
            background-color: #f9f9f9;
        }
        
        .action-btn {
            padding: 5px 10px;
            border-radius: 5px;
            border: none;
            cursor: pointer;
            margin-right: 5px;
            font-size: 0.9rem;
            transition: background-color 0.3s;
        }
        
        .btn-edit {
            background-color: #28a745;
            color: white;
        }
        
        .btn-edit:hover {
            background-color: #218838;
        }
        
        .btn-delete {
            background-color: #dc3545;
            color: white;
        }
        
        .btn-delete:hover {
            background-color: #c82333;
        }
        
        .btn-top {
            background-color: #ffc107;
            color: #212529;
        }
        
        .btn-top:hover {
            background-color: #e0a800;
        }
        
        .btn-untop {
            background-color: #6c757d;
            color: white;
        }
        
        .btn-untop:hover {
            background-color: #5a6268;
        }
        
        .btn-ban {
            background-color: #fd7e14;
            color: white;
        }
        
        .btn-ban:hover {
            background-color: #e0a800;
        }
        
        .badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
            font-weight: bold;
        }
        
        .badge-top {
            background-color: #ff69b4;
            color: white;
        }
        
        .message {
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        
        .message-success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .message-error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .message-info {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }
        
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
            z-index: 1000;
            align-items: center;
            justify-content: center;
        }
        
        .modal-content {
            background-color: white;
            border-radius: 10px;
            width: 90%;
            max-width: 600px;
            padding: 25px;
            position: relative;
        }
        
        .close-modal {
            position: absolute;
            top: 15px;
            right: 20px;
            font-size: 1.5rem;
            cursor: pointer;
            color: #666;
        }
        
        .modal-title {
            color: #d63384;
            margin-top: 0;
            margin-bottom: 20px;
        }
        
        .form-control {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            margin-bottom: 15px;
        }
        
        .form-control:focus {
            border-color: #ff69b4;
            outline: none;
        }
        
        textarea.form-control {
            min-height: 150px;
            resize: vertical;
        }
        
        .btn-submit {
            background-color: #ff69b4;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
        }
        
        .btn-submit:hover {
            background-color: #d63384;
        }
        
        .logout-btn {
            margin-top: 20px;
            text-align: center;
        }
        
        .logout-btn a {
            color: white;
            text-decoration: none;
            display: block;
            padding: 10px;
            background-color: rgba(255,255,255,0.1);
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        
        .logout-btn a:hover {
            background-color: rgba(255,255,255,0.2);
        }
        
        @media (max-width: 768px) {
            .sidebar {
                width: 100%;
                height: auto;
                position: relative;
            }
            
            .main-content {
                margin-left: 0;
                padding: 20px;
            }
            
            .data-table th:nth-child(4), 
            .data-table td:nth-child(4),
            .data-table th:nth-child(5), 
            .data-table td:nth-child(5) {
                display: none;
            }
        }
    </style>
</head>
<body>
    <div class="sidebar col-md-3 col-lg-2 d-md-block">
        <div class="sidebar-header">
            <h2><?php echo SITE_NAME; ?> 管理后台</h2>
        </div>
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link" href="index.php">
                    <i class="fas fa-tachometer-alt"></i> 仪表盘
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link active" href="confessions.php">
                    <i class="fas fa-heart"></i> 表白管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="dailies.php">
                    <i class="fas fa-coffee"></i> 日常管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="announcements.php">
                    <i class="fas fa-bullhorn"></i> 公告管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="comments.php">
                    <i class="fas fa-comments"></i> 评论管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="prohibited_words.php">
                    <i class="fas fa-ban"></i> 违禁词管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="banned_ips.php">
                    <i class="fas fa-shield-alt"></i> 封禁管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="settings.php">
                    <i class="fas fa-cog"></i> 系统设置
                </a>
            </li>
        </ul>
        
        <div class="logout-btn">
            <a href="logout.php">
                <i class="fas fa-sign-out-alt"></i> 退出登录
            </a>
        </div>
    </div>
    
    <main class="main-content">
        <h1 class="page-title"><i class="fas fa-heart"></i> 表白管理</h1>
        
        <?php if (!empty($message)): ?>
            <div class="message message-<?php echo $message_type; ?>">
                <?php echo $message; ?>
            </div>
        <?php endif; ?>
        
        <div class="table-container">
            <table class="data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>表白者</th>
                        <th>被表白人</th>
                        <th>内容</th>
                        <th>IP地址</th>
                        <th>发布时间</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (count($confessions) > 0): ?>
                        <?php foreach ($confessions as $confession): ?>
                            <tr>
                                <td><?php echo $confession['id']; ?></td>
                                <td><?php echo $confession['is_anonymous'] ? '匿名用户' : htmlspecialchars($confession['confessor']); ?></td>
                                <td><?php echo htmlspecialchars($confession['target_person']); ?></td>
                                <td><?php echo mb_strlen($confession['content']) > 30 ? mb_substr($confession['content'], 0, 30) . '...' : htmlspecialchars($confession['content']); ?></td>
                                <td><?php echo $confession['ip_address']; ?></td>
                                <td><?php echo date('Y-m-d H:i', strtotime($confession['created_at'])); ?></td>
                                <td><?php echo $confession['is_top'] ? '<span class="badge badge-top">已置顶</span>' : ''; ?></td>
                                <td>
                                    <button class="action-btn btn-edit" onclick="openEditModal(<?php echo $confession['id']; ?>, '<?php echo addslashes($confession['content']); ?>')">
                                        <i class="fas fa-edit"></i> 编辑
                                    </button>
                                    <?php if ($confession['is_top']): ?>
                                        <a href="confessions.php?action=untop&id=<?php echo $confession['id']; ?>" class="action-btn btn-untop" onclick="return confirm('确定要取消置顶吗？')">
                                            <i class="fas fa-thumbtack"></i> 取消置顶
                                        </a>
                                    <?php else: ?>
                                        <a href="confessions.php?action=top&id=<?php echo $confession['id']; ?>" class="action-btn btn-top" onclick="return confirm('确定要置顶吗？')">
                                            <i class="fas fa-thumbtack"></i> 置顶
                                        </a>
                                    <?php endif; ?>
                                    <a href="confessions.php?action=ban&id=<?php echo $confession['id']; ?>" class="action-btn btn-ban" onclick="return confirm('确定要封禁此IP吗？')">
                                        <i class="fas fa-ban"></i> 封禁IP
                                    </a>
                                    <a href="confessions.php?action=delete&id=<?php echo $confession['id']; ?>" class="action-btn btn-delete" onclick="return confirm('确定要删除吗？此操作不可恢复！')">
                                        <i class="fas fa-trash"></i> 删除
                                    </a>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="8" style="text-align: center; padding: 20px;">暂无表白内容</td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </main>
    
    <!-- 编辑模态框 -->
    <div id="editModal" class="modal">
        <div class="modal-content">
            <span class="close-modal" onclick="closeEditModal()">&times;</span>
            <h2 class="modal-title">编辑表白内容</h2>
            <form method="post">
                <input type="hidden" id="editId" name="id">
                <textarea class="form-control" id="editContent" name="content" required></textarea>
                <button type="submit" name="edit_confession" class="btn-submit">保存修改</button>
            </form>
        </div>
    </div>
    
    <script>
        // 编辑模态框相关
        const modal = document.getElementById('editModal');
        
        function openEditModal(id, content) {
            document.getElementById('editId').value = id;
            document.getElementById('editContent').value = content;
            modal.style.display = 'flex';
        }
        
        function closeEditModal() {
            modal.style.display = 'none';
        }
        
        // 点击模态框外部关闭
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = 'none';
            }
        }
    </script>
</body>
</html>
